<template>
  <el-dialog
    v-model="dialogVisible"
    width="90vw"
    :before-close="handleClose"
    class="role-detail-dialog"
    :show-close="false"
    top="5vh"
  >
    <template #header>
      <div class="dialog-header">
        <div class="header-title"></div>
        <div class="close-btn" @click="handleClose">×</div>
      </div>
    </template>

    <div class="dialog-content">
      <!-- 左侧个人信息 -->
      <div class="left-info">
        <div class="avatar-section">
          <div class="main-avatar">
            <img :src="photoList.length > 0 ? photoList[0] : ''" alt="头像" />
          </div>
        </div>

        <div class="personal-info">
          <div class="name-section">
            <div class="name-left">
              <span class="name">{{ roleDetails['686e0c6fd9147824a38a6294'] || '子涵' }}</span>
              <span class="gender-icon" :class="genderDisplay === '♀' ? 'female' : 'male'">
                {{ genderDisplay }}
              </span>
            </div>
            <span class="status-badge">已成交3单</span>
          </div>

          <div class="location">{{ locationText }}</div>

          <div class="stats-horizontal">
            <div class="stat-item">
              <span class="stat-value"
                >{{ Number(roleDetails['686e0f429104eb90ad4247a5']) || '168' }}cm</span
              >
              <span class="stat-label">身高</span>
            </div>
            <div class="stat-item">
              <span class="stat-value"
                >{{ Number(roleDetails['686e0f429104eb90ad4247a6']) || '47' }}kg</span
              >
              <span class="stat-label">体重</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ roleDetails['688051358c409b88b8519759'] || '---' }}</span>
              <span class="stat-label">三围</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ roleDetails['686e0f429104eb90ad4247a8'] }}</span>
              <span class="stat-label">鞋码</span>
            </div>
          </div>

          <div class="divider"></div>

          <!-- 身份标签部分 -->
          <div class="identity-section">
            <h4>身份标签</h4>
            <div class="identity-tags" v-if="identityTags.length > 0">
              <span
                v-for="(tag, index) in identityTags"
                :key="index"
                class="identity-tag"
                :class="`tag-color-${index % 6}`"
              >
                {{ tag }}
              </span>
            </div>
            <div v-else class="no-tags">暂无标签</div>
          </div>

          <div class="divider"></div>

          <div class="description" v-if="roleDetails['68804fc68c409b88b85196d1']">
            <h4>个人简介</h4>
            <p>{{ roleDetails['68804fc68c409b88b85196d1'] }}</p>
          </div>
        </div>
      </div>

      <!-- 右侧照片展示区域 -->
      <div class="right-photos">
        <!-- 标签页导航 -->
        <div class="right-header-tabs">
          <div
            class="tab-item"
            :class="{ active: activeTab === 'photos' }"
            @click="activeTab = 'photos'"
          >
            照片/视频
          </div>
          <div
            class="tab-item"
            :class="{ active: activeTab === 'cards' }"
            @click="activeTab = 'cards'"
          >
            模卡
          </div>
        </div>

        <!-- 照片展示区域 -->
        <div class="photos-container">
          <div v-if="activeTab === 'photos'" class="photos-display">
            <div
              v-for="(media, index) in mediaList"
              :key="index"
              class="media-item"
              :class="`media-count-${mediaList.length}`"
            >
              <img v-if="media.type === 'photo'" :src="media.url" alt="照片" />
              <div v-else-if="media.type === 'video'" class="video-container">
                <video
                  :src="media.url"
                  preload="metadata"
                  class="video-player"
                  @click="playVideo"
                  @ended="onVideoEnded"
                >
                  您的浏览器不支持视频播放
                </video>
                <div class="play-button-overlay" @click="playVideo">
                  <div class="play-icon">▶</div>
                </div>
              </div>
            </div>
          </div>

          <div v-if="activeTab === 'cards'" class="cards-grid">
            <div class="card-item" v-for="(card, index) in modelCard" :key="index">
              <img :src="card" alt="模卡" />
            </div>
          </div>
        </div>

        <!-- 底部数据条（始终占位，非模卡时透明） -->
        <div class="bottom-stats" :class="{ inactive: activeTab !== 'cards' }">
          <div class="stat-bar">
            <span class="stat-text">{{ roleDetails['686e0c6fd9147824a38a6294'] }}</span>
            <span class="gender-symbol">{{ genderDisplay }}</span>
          </div>
          <div class="stat-items">
            <div class="stat-item">
              <span class="value">{{ Number(roleDetails['686e0f429104eb90ad4247a5']) }}cm</span>
              <span class="label">身高</span>
            </div>
            <div class="stat-item">
              <span class="value">{{ Number(roleDetails['686e0f429104eb90ad4247a6']) }}kg</span>
              <span class="label">体重</span>
            </div>
            <div class="stat-item">
              <span class="value">{{ roleDetails['688051358c409b88b8519759'] }}</span>
              <span class="label">三围</span>
            </div>
            <div class="stat-item">
              <span class="value">{{ roleDetails['686e0f429104eb90ad4247a8'] }}</span>
              <span class="label">鞋码</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { apiService } from '@/utils/api'
import { getAreaName, getProvinceAndCity } from '@/utils/areaCode'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  roleData: {
    type: [Object, String],
    default: () => ({}),
  },
})

const emit = defineEmits(['update:visible'])

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val),
})

const activeTab = ref('photos')
const roleDetails = ref({})
const videoRefs = ref([])

// 播放视频
const playVideo = (event) => {
  const videoContainer = event.currentTarget.closest('.video-container')
  const video = videoContainer.querySelector('video')
  const playButton = videoContainer.querySelector('.play-button-overlay')

  if (video.paused) {
    video.play()
    playButton.style.display = 'none'
  } else {
    video.pause()
    playButton.style.display = 'flex'
  }
}

// 视频播放结束时的处理
const onVideoEnded = (event) => {
  const videoContainer = event.target.closest('.video-container')
  const playButton = videoContainer.querySelector('.play-button-overlay')
  playButton.style.display = 'flex'
}

// 从roleDetails中获取照片列表
const photoList = computed(() => {
  if (roleDetails.value['687633c7ef700e94a0d82b59']) {
    try {
      const photoData = roleDetails.value['687633c7ef700e94a0d82b59']
      const photos = JSON.parse(photoData)

      // 检查是否是数组
      if (Array.isArray(photos) && photos.length > 0) {
        return photos
          .map((photo) => {
            // 如果是字符串，直接返回
            if (typeof photo === 'string') {
              return photo
            }
            // 如果是对象且有DownloadUrl属性
            else if (photo && photo.DownloadUrl) {
              return photo.DownloadUrl
            }
            // 其他情况
            return ''
          })
          .filter((url) => url)
      }
    } catch (error) {
      console.error('解析照片数据失败:', error, roleDetails.value['687633c7ef700e94a0d82b59'])
    }
  }
  return []
})

// 从roleDetails中获取模卡列表
const modelCard = computed(() => {
  if (roleDetails.value['688050b38c409b88b851973c']) {
    try {
      const cardData = roleDetails.value['688050b38c409b88b851973c']
      const cards = JSON.parse(cardData)

      // 检查是否是数组
      if (Array.isArray(cards) && cards.length > 0) {
        return cards
          .map((card) => {
            // 如果是字符串，直接返回
            if (typeof card === 'string') {
              return card
            }
            // 如果是对象且有DownloadUrl属性
            else if (card && card.DownloadUrl) {
              return card.DownloadUrl
            }
            // 其他情况
            return ''
          })
          .filter((url) => url)
      }
    } catch (error) {
      console.error('解析模卡数据失败:', error, roleDetails.value['688050b38c409b88b851973c'])
    }
  }
  return []
})

// 从roleDetails中获取视频列表
const videoList = computed(() => {
  if (roleDetails.value['688050b38c409b88b851973b']) {
    try {
      const videoData = roleDetails.value['688050b38c409b88b851973b']
      const videos = JSON.parse(videoData)

      // 检查是否是数组
      if (Array.isArray(videos) && videos.length > 0) {
        return videos
          .map((video) => {
            // 如果是字符串，直接返回
            if (typeof video === 'string') {
              return video
            }
            // 如果是对象且有DownloadUrl属性
            else if (video && video.DownloadUrl) {
              return video.DownloadUrl
            }
            // 其他情况
            return ''
          })
          .filter((url) => url)
      }
    } catch (error) {
      console.error('解析视频数据失败:', error, roleDetails.value['688050b38c409b88b851973b'])
    }
  }
  return []
})

// 合并照片和视频列表
const mediaList = computed(() => {
  const photos = photoList.value.map((url) => ({ type: 'photo', url }))
  const videos = videoList.value.map((url) => ({ type: 'video', url }))
  return [...photos, ...videos]
})

// 获取地区名称
const locationText = computed(() => {
  const province = getAreaName(roleDetails.value['686e0f429104eb90ad4247a3'])

  // 检查工作范围
  const workRange = roleDetails.value['686e0f429104eb90ad4247a4']
  let rangeText = '仅本地'

  if (workRange === '470a70a3-4fc3-4c4c-bea6-3bd2a2b7556c') {
    rangeText = '全国'
  }

  return `${province} · ${rangeText}`
})

// 获取性别显示
const genderDisplay = computed(() => {
  const genderCode = roleDetails.value['686e0c6fd9147824a38a6295']
  return genderCode === '2d5e8f66-b757-4a60-b7e7-e7c2a3c716bf' ? '♀' : '♂'
})

// 处理身份标签
const identityTags = computed(() => {
  if (!roleDetails.value['68a2c617703512ca0fc111e3']) {
    return []
  }

  try {
    // 尝试解析JSON
    if (typeof roleDetails.value['68a2c617703512ca0fc111e3'] === 'string') {
      const parsed = JSON.parse(roleDetails.value['68a2c617703512ca0fc111e3'])
      return Array.isArray(parsed) ? parsed : []
    }
    // 如果已经是数组，直接使用
    else if (Array.isArray(roleDetails.value['68a2c617703512ca0fc111e3'])) {
      return roleDetails.value['68a2c617703512ca0fc111e3']
    }
    return []
  } catch (error) {
    console.error('解析身份标签失败:', error)
    return []
  }
})

// 获取角色详情
const getRoleData = async () => {
  try {
    // 如果传入的是字符串（角色ID），则调用API获取详情
    if (typeof props.roleData === 'string') {
      const res = await apiService.getFilterRows({
        worksheetId: '6876257b872d9db2c7ba5297',
        filters: [
          {
            controlId: 'rowid',
            dataType: 2,
            spliceType: 1,
            filterType: 2,
            value: props.roleData,
          },
        ],
      })
      console.log('getRoleData 结果:', res)

      if (res && res.rows && res.rows.length > 0) {
        const filteredRows = res.rows.filter((item) => item['rowid'] === props.roleData)
        if (filteredRows.length > 0) {
          roleDetails.value = filteredRows[0]
          console.log('获取到的角色详情:', roleDetails.value)
          console.log(
            '视频地址:',
            JSON.parse(roleDetails.value['688050b38c409b88b851973b'])[0].DownloadUrl,
          )
        } else {
          console.warn('未找到匹配的角色ID:', props.roleData)
        }
      } else {
        console.warn('API返回数据为空')
      }
    } else {
      // 如果传入的是对象，直接使用
      roleDetails.value = props.roleData
    }
  } catch (error) {
    console.error('获取角色详情失败:', error)
  }
}

watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      console.log('显示角色详情，传入数据:', props.roleData)
      getRoleData()
    }
  },
  { immediate: true },
)

const handleClose = () => {
  // 暂停所有正在播放的视频并重置到开始位置
  const videos = document.querySelectorAll('.video-player')
  videos.forEach((video) => {
    if (!video.paused) {
      video.pause()
    }
    video.currentTime = 0 // 重置到开始位置
  })

  // 显示所有播放按钮
  const playButtons = document.querySelectorAll('.play-button-overlay')
  playButtons.forEach((button) => {
    button.style.display = 'flex'
  })

  dialogVisible.value = false
}
</script>

<style scoped>
.role-detail-dialog :deep(.el-dialog) {
  margin: 0;
  height: 85vh;
  max-height: 85vh;
  border-radius: 12px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.role-detail-dialog :deep(.el-dialog__header) {
  padding: 0;
  border-bottom: 1px solid #eee;
}

.role-detail-dialog :deep(.el-dialog__body) {
  padding: 0;
  flex: 1;
  overflow: hidden;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 50px;
  flex-shrink: 0;
}

.header-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.close-btn {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background: #f5f5f5;
  color: #333;
}

.dialog-content {
  display: flex;
  height: 100%;
  overflow: hidden;
}

.left-info {
  width: 320px;
  padding: 16px;
  border-right: 1px solid #eee;
  display: flex;
  flex-direction: column;
  gap: 12px;
  overflow-y: auto;
  max-height: 100%;
}

.avatar-section {
  text-align: center;
}

.main-avatar {
  width: 200px;
  height: 200px;
  border-radius: 4px;
  overflow: hidden;
  margin: 0 auto 12px;
  background: #f5f5f5;
}

.main-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.personal-info {
  flex: 1;
}

.name-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.name-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.gender-icon {
  font-size: 16px;
}

.gender-icon.female {
  color: #ff69b4;
}

.gender-icon.male {
  color: #409eff;
}

.status-badge {
  color: #ff69b4;
  padding: 2px 8px;
  font-size: 12px;
}

.location {
  color: #666;
  font-size: 14px;
  margin-bottom: 20px;
}

.stats-horizontal {
  display: flex;
  justify-content: space-between;
  gap: 15px;
  margin-bottom: 15px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  color: black;
  display: block;
  font-size: 14px;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #999;
}

.divider {
  height: 1px;
  background: #eee;
  margin: 15px 0;
}

.identity-section h4 {
  font-size: 12px;
  color: #999;
  margin-bottom: 10px;
}

.identity-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 15px;
}

.identity-tag {
  padding: 4px 12px;
  border: 1px solid;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.identity-tag.tag-color-0 {
  background: #f0f9ff;
  border-color: #0ea5e9;
  color: #0ea5e9;
}

.identity-tag.tag-color-1 {
  background: #fef3c7;
  border-color: #f59e0b;
  color: #f59e0b;
}

.identity-tag.tag-color-2 {
  background: #f0fdf4;
  border-color: #10b981;
  color: #10b981;
}

.identity-tag.tag-color-3 {
  background: #fce7f3;
  border-color: #ec4899;
  color: #ec4899;
}

.identity-tag.tag-color-4 {
  background: #f3e8ff;
  border-color: #8b5cf6;
  color: #8b5cf6;
}

.identity-tag.tag-color-5 {
  background: #fef2f2;
  border-color: #ef4444;
  color: #ef4444;
}

.identity-section {
  margin-bottom: 15px;
}

.description h4 {
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
}

.description p {
  font-size: 12px;
  color: #666;
  line-height: 1.5;
}

.right-photos {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.right-header-tabs {
  display: flex;
  gap: 40px;
  padding: 16px 16px 0 16px;
  margin-top: -30px;
  border-bottom: 1px solid #eee;
  flex-shrink: 0;
}

.right-header-tabs .tab-item {
  padding: 15px 0;
  font-size: 24px;
  margin-left: 100px;
  color: #666;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.3s ease;
}

.right-header-tabs .tab-item.active {
  color: #333;
  border-bottom: none;
  position: relative;
}

.right-header-tabs .tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 50%;
  transform: translateX(-50%);
  width: 2em;
  height: 3px;
  background-color: #ff69b4;
  border-radius: 2px;
}

.photos-container {
  flex: 1;
  padding: 16px 16px 5px 16px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.photos-display {
  flex: 1;
  display: grid;
  gap: 6px;
  align-content: start;
  overflow: hidden;
  height: 100%;
  max-height: calc(85vh - 220px);
}

/* 媒体展示样式 - 替换原来的照片样式 */
.media-item {
  border-radius: 8px;
  overflow: hidden;
  background: #f5f5f5;
  width: 100%;
}

.media-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 视频容器样式 */
.video-container {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  background: #f5f5f5;
  cursor: pointer;
}

.video-player {
  width: 100%;
  height: 100%;
  object-fit: cover;
  background: #000;
  display: block;
}

.play-button-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  z-index: 1;
}

.play-button-overlay:hover {
  background: rgba(0, 0, 0, 0.5);
}

.play-icon {
  width: 60px;
  height: 60px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #333;
  transition: all 0.3s ease;
  margin-left: 4px; /* 视觉居中调整 */
}

.play-button-overlay:hover .play-icon {
  background: rgba(255, 255, 255, 1);
  transform: scale(1.1);
}

/* 1个媒体 - 居中显示，适合竖向 */
.photos-display:has(.media-count-1) {
  grid-template-columns: 1fr;
  justify-items: center;
}

.media-count-1 {
  max-width: 50%;
  aspect-ratio: 3/4;
}

/* 2个媒体 - 两列，竖向排列 */
.photos-display:has(.media-count-2) {
  grid-template-columns: 1fr 1fr;
}

.media-count-2 {
  aspect-ratio: 3/4;
}

/* 3个媒体 - 三列均匀排列 */
.photos-display:has(.media-count-3) {
  grid-template-columns: 1fr 1fr 1fr;
}

.media-count-3 {
  aspect-ratio: 3/4;
}

/* 4个媒体 - 2行2列 */
.photos-display:has(.media-count-4) {
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
}

.media-count-4 {
  aspect-ratio: 3/4;
}

/* 5个媒体 - 第一行2个，第二行3个 */
.photos-display:has(.media-count-5) {
  grid-template-columns: repeat(6, 1fr);
  grid-template-rows: 1fr 1fr;
}

.media-count-5:nth-child(1) {
  grid-column: 2 / 4;
  aspect-ratio: 3/4;
}

.media-count-5:nth-child(2) {
  grid-column: 4 / 6;
  aspect-ratio: 3/4;
}

.media-count-5:nth-child(3) {
  grid-column: 1 / 3;
  aspect-ratio: 3/4;
}

.media-count-5:nth-child(4) {
  grid-column: 3 / 5;
  aspect-ratio: 3/4;
}

.media-count-5:nth-child(5) {
  grid-column: 5 / 7;
  aspect-ratio: 3/4;
}

/* 6个媒体 - 2行3列 */
.photos-display:has(.media-count-6) {
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr;
}

.media-count-6 {
  aspect-ratio: 3/4;
}

.cards-grid {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 12px;
  overflow: hidden;
  height: 100%;
  max-height: calc(85vh - 220px);
  align-content: start;
}

.card-item {
  border-radius: 8px;
  overflow: hidden;
  background: #f5f5f5;
}

.card-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.bottom-stats {
  background: rgba(235, 65, 150, 0.9);
  padding: 12px 16px;
  margin: 0 40px 16px 40px;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 70px;
  box-sizing: border-box;
  flex-shrink: 0;
  transition: opacity 0.2s ease;
}

.bottom-stats.inactive {
  opacity: 0;
  pointer-events: none;
}

.stat-bar {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stat-text {
  font-size: 24px;
}

.gender-symbol {
  font-size: 16px;
}

.stat-items {
  display: flex;
  gap: 30px;
}

.stat-items .stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.stat-items .stat-item .value {
  font-size: 15px;
  font-weight: 700;
  margin-bottom: 1px;
}

.stat-items .stat-item .label {
  margin-top: 5px;
  font-size: 10px;
  opacity: 0.8;
}

.no-tags {
  color: #999;
  font-size: 12px;
  font-style: italic;
}
</style>
